/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ttt.nor2.alarm;

import com.ttt.nor2.config.CfgAlarm;
import com.ttt.nor2.db.EmpTakeExchange;
import com.ttt.nor2.util.ExceptionUtil;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;

/**
 *
 * @author anuphabm
 */
public class SendSMS2Webservice {

    private Logger logger = Logger.getLogger(SendSMS2Webservice.class);
    private HashMap hmEmp;
    private CfgAlarm cfg;
    private EmpTakeExchange emp;
    private Hashtable buffEmp;

    SendSMS2Webservice(HashMap hmEmp, CfgAlarm cfg) {
        this.hmEmp = hmEmp;
        this.cfg = cfg;
        buffEmp = new Hashtable();
    }

    private boolean chkDupEmp(String empCode) {
        boolean chk = false;
        if (buffEmp.get(empCode) == null) {
            buffEmp.put(empCode, empCode);
            chk = true;
        }
        return chk;
    }

    public boolean loopSend() {
        boolean sendStatus = false;
        if (hmEmp != null) {
            Iterator it = hmEmp.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                emp = (EmpTakeExchange) hmEmp.get(key);
                // check emp_id manager
                logger.info(emp.getAlarm().getTransid() + " m_id[" + emp.getEmpManager() + "]");
                logger.info(emp.getAlarm().getTransid() + " s_id[" + emp.getEmpSupervisor() + "]");
                logger.info(emp.getAlarm().getTransid() + " o_id[" + emp.getEmpOperator() + "]");
                logger.info(emp.getAlarm().getTransid() + " location[" + emp.getLocation() + "]");
                logger.info(emp.getAlarm().getTransid() + " exchange name[" + emp.getExchangeName() + "]");
                logger.info(emp.getAlarm().getTransid() + " alarm[" + emp.getAlarm().getAlarm_desc() + "]");

                String mobile = findMobileEmp(emp.getEmpManager());
                logger.info(emp.getAlarm().getTransid() + " Mobile Manager[" + mobile + "]");
                if (!mobile.equalsIgnoreCase("")) {
                    //chkDupMsgOut(mobile);
                    if (chkDupEmp(Integer.toString(emp.getEmpManager()))) {
                        sendStatus = send(mobile);
                    }
                }
                // check emp_id supervisor
                mobile = findMobileEmp(emp.getEmpSupervisor());
                logger.info(emp.getAlarm().getTransid() + " Mobile Supervisor[" + mobile + "]");
                if (!mobile.equalsIgnoreCase("")) {
                    //chkDupMsgOut(mobile);
                    if (chkDupEmp(Integer.toString(emp.getEmpSupervisor()))) {
                        sendStatus = send(mobile);
                    }
                }
                // check emp_id operator
                mobile = findMobileEmp(emp.getEmpOperator());
                logger.info(emp.getAlarm().getTransid() + " Mobile Operator[" + mobile + "]");
                if (!mobile.equalsIgnoreCase("")) {
                    //chkDupMsgOut(mobile);
                    if (chkDupEmp(Integer.toString(emp.getEmpOperator()))) {
                        sendStatus = send(mobile);
                    }
                }
                // spacial center request fault all city

            }
        }
        return sendStatus;
    }

    private boolean isChkDupMsgOut(String mobile, String msgout) {

        boolean chkdup = true; //not send default
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "";
        if (isChkInsert(mobile, msgout)) {

            sql = "SELECT * FROM msg_dup AS m WHERE m.mobile =  ? AND m.message = ? " +
                    "and msg_count < 6 and  now()  > stamptime + INTERVAL " + cfg.getChkdup() + " MINUTE ";

            logger.debug(emp.getAlarm().getTransid() + " sql[" + sql + "][" + mobile + "][" + msgout + "]");
            try {
               pstmt = cfg.getConn().prepareStatement(sql);
                pstmt.setString(1, mobile);
                pstmt.setString(2, msgout);
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    chkdup = false;
                }else{
                    chkdup = true;
                }
                sql = "update msg_dup set msg_count = msg_count+1, stamptime=now() where mobile = ? and message = ?";
                rs.close();
                pstmt.close();
            } catch (SQLException e) {
                logger.error("Exception query check duplicate error " + ExceptionUtil.getStackTrace(e));
                System.exit(-1);
            }

        } else {
            sql = "insert into msg_dup(mobile, message, msg_count, stamptime)values(?, ?, 1, now()) ";
            chkdup = false;

        }

        // execute sql
        try {
            pstmt = cfg.getConn().prepareStatement(sql);
            pstmt.setString(1, mobile);
            pstmt.setString(2, msgout);
            pstmt.executeUpdate();
            pstmt.close();
        } catch (SQLException e) {
            logger.error("Exception query check duplicate error " + ExceptionUtil.getStackTrace(e));
            chkdup = true;
        }


        logger.info(emp.getAlarm().getTransid() + " return check duplicate [" + chkdup + "]");
        return chkdup;
    }

    private String findMobileEmp(int empid) {

        String sql = "SELECT e.emp_name, e.mobile, w.status_work FROM work_day AS w ";
        sql += "Inner Join employee AS e ON w.emp_id = e.emp_id where ";
        sql += "w.status_work = 'Y' and w.day_work = DAYOFWEEK(now()) ";
        sql += "and  (date_format(now(),'%H%i') > w.time_work_b ";
        sql += "or date_format(now(),'%H%i') < w.time_work_e)and e.emp_id=?";
        logger.debug("sql[" + sql + "]" + empid);
        String mobile = "";
        try {
            PreparedStatement pstmt = cfg.getConn().prepareStatement(sql);
            pstmt.setInt(1, empid);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                mobile = rs.getString("mobile");
                if (mobile == null) {
                    return "";
                }
            }
        } catch (SQLException e) {
            logger.error("Exception check status " + ExceptionUtil.getStackTrace(e));
            return "";
        }
        return mobile;

    }

    private boolean send(String mobile) {
        boolean statusSend = false;
        String msgOut = "";
        msgOut = emp.getLocation() + " " + emp.getExchangeName() + " " + emp.getAlarm().getAlarm_desc() + " ";
        msgOut += emp.getAlarm().getTimeAlarm() + " " + emp.getAlarm().getAlarm_prop();
        logger.debug(msgOut);
        if (isChkDupMsgOut(mobile, msgOut)) {
            return statusSend;
        }
        String transid = emp.getAlarm().getTransid();
        StringBuffer data = new StringBuffer();
        data.append("mobile=").append(mobile).append("&msgout=").append(msgOut).append("&transid=").append(transid);
        String dataPost = data.toString();
        PostMethod post = new PostMethod(cfg.getPostUrl());
        logger.info("Post to url : " + cfg.getPostUrl());

        try {
            RequestEntity ent = new StringRequestEntity(dataPost, "application/x-www-form-urlencoded", "UTF-8");
            post.setRequestEntity(ent);
            post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            HttpClient c = new HttpClient();
            c.getParams().setSoTimeout(5000);
            c.getParams().setConnectionManagerTimeout(5000);

            c.executeMethod(post);

            if ((post.getStatusCode() == HttpStatus.SC_OK) || (post.getStatusCode() == 202)) {
                InputStream is = post.getResponseBodyAsStream();
                String line;
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                StringBuffer b = new StringBuffer();

                while ((line = in.readLine()) != null) {
                    String newLine = line + "\\n";
                    b.append(newLine);
                }
                String repResult = b.toString().trim();
                logger.info("Post value : " + dataPost);
                logger.info("Post Result: " + repResult);
                statusSend = true;
            }


        } catch (Exception e) {
            logger.error("Exception post to url " + cfg.getPostUrl() + " error! " + ExceptionUtil.getStackTrace(e));
        } finally {
            post.releaseConnection();
        }

        return statusSend;
    }

    private boolean isChkInsert(String mobile, String msgout) {
        boolean chkInsert = false;
        try {
            String sql = "select * from msg_dup where mobile =? and message =?";
            PreparedStatement pstmt = cfg.getConn().prepareStatement(sql);
            pstmt.setString(1, mobile);
            pstmt.setString(2, msgout);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                chkInsert = true;
            }
            rs.close();
            pstmt.close();
        } catch (SQLException e) {
            logger.error("Exception query msg_dup error " + ExceptionUtil.getStackTrace(e));
            System.exit(-1);
        } catch(Exception eb){
            logger.error("Exception other " + ExceptionUtil.getStackTrace(eb));
        }
        return chkInsert;
    }
}
